{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-04-01T15:22:28.151517Z",
     "start_time": "2025-04-01T15:22:28.148125Z"
    }
   },
   "source": [
    "from sklearn.datasets import load_iris, fetch_20newsgroups, fetch_california_housing\n",
    "from sklearn.model_selection import train_test_split, GridSearchCV\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.feature_extraction.text import TfidfVectorizer\n",
    "from sklearn.naive_bayes import MultinomialNB\n",
    "from sklearn.metrics import classification_report\n",
    "from sklearn.feature_extraction import DictVectorizer\n",
    "from sklearn.tree import DecisionTreeClassifier, export_graphviz\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "from sklearn.metrics import roc_auc_score\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "import time"
   ],
   "outputs": [],
   "execution_count": 14
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-01T14:56:56.177635Z",
     "start_time": "2025-04-01T14:56:56.168179Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#鸢尾花数据集，查看特征，目标，样本量\n",
    "\n",
    "li = load_iris()  #li是一个类对象，包含了鸢尾花数据集的特征值，目标值，样本量等信息\n",
    "\n",
    "print(\"获取特征值\")\n",
    "print(type(li.data))\n",
    "print(\"-\" * 50)\n",
    "print(li.data.shape)\n",
    "print(li.data[:5])\n",
    "print(li.feature_names)\n",
    "li.target  #目标值"
   ],
   "id": "c12c3c77d260fe0a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "获取特征值\n",
      "<class 'numpy.ndarray'>\n",
      "--------------------------------------------------\n",
      "(150, 4)\n",
      "[[5.1 3.5 1.4 0.2]\n",
      " [4.9 3.  1.4 0.2]\n",
      " [4.7 3.2 1.3 0.2]\n",
      " [4.6 3.1 1.5 0.2]\n",
      " [5.  3.6 1.4 0.2]]\n",
      "['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
       "       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
       "       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n",
       "       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n",
       "       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-01T14:55:53.802429Z",
     "start_time": "2025-04-01T14:55:53.796571Z"
    }
   },
   "cell_type": "code",
   "source": "li.DESCR  #数据集描述",
   "id": "50abcd697ed0dfc7",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'.. _iris_dataset:\\n\\nIris plants dataset\\n--------------------\\n\\n**Data Set Characteristics:**\\n\\n:Number of Instances: 150 (50 in each of three classes)\\n:Number of Attributes: 4 numeric, predictive attributes and the class\\n:Attribute Information:\\n    - sepal length in cm\\n    - sepal width in cm\\n    - petal length in cm\\n    - petal width in cm\\n    - class:\\n            - Iris-Setosa\\n            - Iris-Versicolour\\n            - Iris-Virginica\\n\\n:Summary Statistics:\\n\\n============== ==== ==== ======= ===== ====================\\n                Min  Max   Mean    SD   Class Correlation\\n============== ==== ==== ======= ===== ====================\\nsepal length:   4.3  7.9   5.84   0.83    0.7826\\nsepal width:    2.0  4.4   3.05   0.43   -0.4194\\npetal length:   1.0  6.9   3.76   1.76    0.9490  (high!)\\npetal width:    0.1  2.5   1.20   0.76    0.9565  (high!)\\n============== ==== ==== ======= ===== ====================\\n\\n:Missing Attribute Values: None\\n:Class Distribution: 33.3% for each of 3 classes.\\n:Creator: R.A. Fisher\\n:Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)\\n:Date: July, 1988\\n\\nThe famous Iris database, first used by Sir R.A. Fisher. The dataset is taken\\nfrom Fisher\\'s paper. Note that it\\'s the same as in R, but not as in the UCI\\nMachine Learning Repository, which has two wrong data points.\\n\\nThis is perhaps the best known database to be found in the\\npattern recognition literature.  Fisher\\'s paper is a classic in the field and\\nis referenced frequently to this day.  (See Duda & Hart, for example.)  The\\ndata set contains 3 classes of 50 instances each, where each class refers to a\\ntype of iris plant.  One class is linearly separable from the other 2; the\\nlatter are NOT linearly separable from each other.\\n\\n.. dropdown:: References\\n\\n  - Fisher, R.A. \"The use of multiple measurements in taxonomic problems\"\\n    Annual Eugenics, 7, Part II, 179-188 (1936); also in \"Contributions to\\n    Mathematical Statistics\" (John Wiley, NY, 1950).\\n  - Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis.\\n    (Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.\\n  - Dasarathy, B.V. (1980) \"Nosing Around the Neighborhood: A New System\\n    Structure and Classification Rule for Recognition in Partially Exposed\\n    Environments\".  IEEE Transactions on Pattern Analysis and Machine\\n    Intelligence, Vol. PAMI-2, No. 1, 67-71.\\n  - Gates, G.W. (1972) \"The Reduced Nearest Neighbor Rule\".  IEEE Transactions\\n    on Information Theory, May 1972, 431-433.\\n  - See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al\"s AUTOCLASS II\\n    conceptual clustering system finds 3 classes in the data.\\n  - Many, many more ...\\n'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-01T15:22:30.776812Z",
     "start_time": "2025-04-01T15:22:30.769566Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#x是特征值，y是标签值\n",
    "x = li.data\n",
    "y = li.target\n",
    "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=1)\n",
    "\n",
    "#进行标准化\n",
    "std = StandardScaler()\n",
    "x_train = std.fit_transform(x_train)\n",
    "x_test = std.transform(x_test)\n"
   ],
   "id": "7a76c3f33dea3d1a",
   "outputs": [],
   "execution_count": 15
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## KNN算法",
   "id": "a640824753a4c481"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-01T15:23:30.787747Z",
     "start_time": "2025-04-01T15:23:30.771828Z"
    }
   },
   "cell_type": "code",
   "source": [
    "knn = KNeighborsClassifier(n_neighbors=5)\n",
    "\n",
    "knn.fit(x_train, y_train)\n",
    "\n",
    "y_predict = knn.predict(x_test)\n",
    "\n",
    "print(\"预测的目标标签：\", y_predict[0:10])\n",
    "\n",
    "print(\"预测的准确率\", knn.score(x_test, y_test))"
   ],
   "id": "3b0555b48f837751",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "预测的目标标签： [0 1 1 0 2 1 2 0 0 2]\n",
      "预测的准确率 0.9736842105263158\n"
     ]
    }
   ],
   "execution_count": 16
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
